package list

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/logger"
	"sg-backend/model/paylog"
	"sg-backend/model/user"
	"sg-backend/utils"
)

type _UserListDto struct {
	Id             uint   `json:"id"`
	Username       string `json:"username"`
	Email          string `json:"email"`
	Mobile         string `json:"mobile"`
	Nickname       string `json:"nickname"`
	Gender         uint   `json:"gender"`
	Avatar         string `json:"avatar"`
	Dept           []uint `json:"dept"`
	Role           []uint `json:"role"`
	Password       string `json:"password"`
	PasswordSalt   string `json:"passwordSalt"`
	Position       string `json:"position"`
	WxUnionId      string `json:"wxUnionId"`
	DingTalkUserId string `json:"dingTalkUserId"`
	DirectLeader   uint   `json:"directLeader"`
	WxId           string `json:"wxId"`
	IsLock         bool   `json:"isLock"`
	IsFirstLogin   bool   `json:"isFirstLogin"`
	IsActive       bool   `json:"isActive"`
	IsSuperuser    bool   `json:"isSuperuser"`
}

// 收入，支出，成员复杂嵌套json结构
type _typeJson struct {
	TypeList []_itemJson `json:"typeList"`
}

// 1,内容json
type _itemJson struct {
	Name string `json:"name"`
	Icon string `json:"icon"`
}

// AddUser 新增账号
func AddUser(ctx *fiber.Ctx) error {
	// 权限验证
	utils.CheckPermsByTag("UserAccount", global.AuthUser.UserId, "add")

	// 获取数据
	var dataDto _UserListDto
	if err := ctx.BodyParser(&dataDto); err != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("数据解释出错！%s", err),
		})
	}

	// 验证数据
	var Account user.User

	// 1，用户名需要唯一
	noDuplicateName := global.DB.Where(
		"username = ?", dataDto.Username,
	).Find(&Account)
	if noDuplicateName.RowsAffected != 0 {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "用户名已存在！不允许账号重名！",
		})
	}

	// 2，手机号码需要唯一
	if dataDto.Mobile != "" {
		noDuplicateMobile := global.DB.Where(
			"mobile = ?", dataDto.Mobile,
		).Find(&Account)
		if noDuplicateMobile.RowsAffected != 0 {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "此手机号已存在！不允许重复！",
			})
		}
	}

	// 3，邮箱需要唯一
	if dataDto.Email != "" {
		noDuplicateEmail := global.DB.Where(
			"email = ?", dataDto.Mobile,
		).Find(&Account)
		if noDuplicateEmail.RowsAffected != 0 {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "此邮箱号已存在！不允许重复！",
			})
		}
	}

	// 5，生成默认密码
	var passwordSalt = utils.GetRandomString(16)
	var encryptPassword = utils.SHAEncrypt("123456" + passwordSalt)

	// 6，保存到数据库
	avatar := dataDto.Avatar
	if len(dataDto.Avatar) == 0 {
		avatar = "/media/avatar/default.png"
	}
	newAccount := user.User{
		Username:     dataDto.Username,
		Email:        dataDto.Email,
		Mobile:       dataDto.Mobile,
		Nickname:     dataDto.Nickname,
		Gender:       dataDto.Gender,
		Avatar:       avatar,
		Password:     encryptPassword,
		PasswordSalt: passwordSalt,
		IsFirstLogin: true,
		IsActive:     true,
		IsSuperuser:  false,
	}
	cr := global.DB.Create(&newAccount)
	if cr.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("新增用户账号失败！错误：%v", cr.Error),
		})
	}

	// 分类初始化
	// 1，支出分类
	// 仅在无数据时初始化
	var payType []paylog.PayType
	payTypeCheck := global.DB.Where("user_id = ?", newAccount.Id).Find(&payType)
	if payTypeCheck.RowsAffected == 0 {

		// 此用户没有支出分类，需要进行初始化
		payTypeList := []paylog.PayType{
			{Name: "吃喝", Icon: "a-008_mifenmiantiao.png", UserId: newAccount.Id},
			{Name: "购物", Icon: "gouwuche.png", UserId: newAccount.Id},
			{Name: "交通", Icon: "a-013_chuzuche.png", UserId: newAccount.Id},
			{Name: "通讯", Icon: "bianmindianhua.png", UserId: newAccount.Id},
			{Name: "医疗", Icon: "a-013_xinjianliucheng.png", UserId: newAccount.Id},
			{Name: "家用", Icon: "a-013_gongsidizhi.png", UserId: newAccount.Id},
			{Name: "学习", Icon: "a-013_yuanchengbangong.png", UserId: newAccount.Id},
			{Name: "社交", Icon: "a-013_youxi.png", UserId: newAccount.Id},
			{Name: "美容", Icon: "a-013_liwufuli.png", UserId: newAccount.Id},
			{Name: "其他", Icon: "a-013_gengduo-37.png", UserId: newAccount.Id},
		}
		cr := global.DB.Create(&payTypeList)
		if cr.Error != nil {
			global.SLog.Errorf("初始化支出分类失败！%s", cr.Error)
			fmt.Printf("初始化支出分类失败！%s \n", cr.Error)
		}
	}

	// 2，收入分类
	var incomeType []paylog.IncomeType
	incomeTypeCheck := global.DB.Where("user_id = ?", newAccount.Id).Find(&incomeType)
	if incomeTypeCheck.RowsAffected == 0 {

		// 此用户没有收入分类，需要进行初始化
		incomeTypeList := []paylog.IncomeType{
			{Name: "工资", Icon: "renminbi_1.png", UserId: newAccount.Id},
			{Name: "兼职", Icon: "a-013_qingjiashenqing-21.png", UserId: newAccount.Id},
			{Name: "转入", Icon: "ershoushichang.png", UserId: newAccount.Id},
			{Name: "理财", Icon: "kehujixi.png", UserId: newAccount.Id},
			{Name: "捡的", Icon: "moneybag.png", UserId: newAccount.Id},
			{Name: "其他", Icon: "shengyizhuanrang.png", UserId: newAccount.Id},
		}
		cr := global.DB.Create(&incomeTypeList)
		if cr.Error != nil {
			global.SLog.Errorf("初始化收入分类失败！%s", cr.Error)
			fmt.Printf("初始化收入分类失败！%s \n", cr.Error)
		}
	}

	// 3，家庭成员
	var familyType []paylog.FamilyType
	familyTypeCheck := global.DB.Where("user_id = ?", newAccount.Id).Find(&familyType)
	if familyTypeCheck.RowsAffected == 0 {

		// 此用户没有家庭成员分类，需要进行初始化
		familyTypeList := []paylog.FamilyType{
			{Name: "自己", Icon: "nanshi_1.png", UserId: newAccount.Id},
			{Name: "家庭", Icon: "jiaren.png", UserId: newAccount.Id},
			{Name: "配偶", Icon: "nvshi_1.png", UserId: newAccount.Id},
			{Name: "儿女", Icon: "haizi.png", UserId: newAccount.Id},
			{Name: "父母", Icon: "037-parents.png", UserId: newAccount.Id},
			{Name: "其他", Icon: "shengyizhuanrang.png", UserId: newAccount.Id},
		}
		cr := global.DB.Create(&familyTypeList)
		if cr.Error != nil {
			global.SLog.Errorf("初始化家庭成员失败！%s", cr.Error)
			fmt.Printf("初始化家庭成员失败！%s \n", cr.Error)
		}
	}
	// 新增成功，写日志
	logger.DbInfo(global.AuthUser.Username, fmt.Sprintf("新增用户账号账号成功！账号：%+v", dataDto))
	return ctx.JSON(fiber.Map{
		"status":  "done",
		"message": "新增用户账号成功！",
	})
}
